# -*- coding: utf-8 -*-
import os

from PyQt5.QtWidgets import QPushButton, QLineEdit, QVBoxLayout, QFrame, QMessageBox, \
    QFileDialog, QHBoxLayout, QLabel, QWidget
from PyQt5.QtCore import Qt, QCoreApplication
import sys
from Window.StudentsUI import Ui_ClientMainWindow
from PyQt5.QtWidgets import QApplication,QMainWindow,QDialog
from ScokerTool import client
import threading
import json
from PIL import Image
import math
import operator
from functools import reduce
from functools import partial
import random

'''
def compare(pic1,pic2):
    
    #:param pic1: 图片1路径
    #:param pic2: 图片2路径
    #:return: 返回对比的结果
    
    image1 = Image.open(pic1)
    image2 = Image.open(pic2)

    histogram1 = image1.histogram()
    histogram2 = image2.histogram()

    differ = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2,histogram1, histogram2)))/len(histogram1))
    return differ
'''


class Students(QMainWindow, Ui_ClientMainWindow):
    def __init__(self):
        super(Students, self).__init__()
        self.anser_list = [['imread', 'imwrite', 'imshow'], \
                      ['img', 'img.shape', 'np.float'], \
                      ['np.fft.fft2', 'np.fft.fftshift', 'ifftshift'], \
                      ['np.fft.fft2', 'f1shift', 'ifft2'], \
                      ['medianBlur', 'blur', 'GaussianBlur'], \
                      ['array', 'np.float32', 'convolve2d'], \
                      ['imread', 'convertScaleAbs', 'addWeighted']]
        self.ran = random.randint(1,7)
        self.start_num = 1
        self.isgetmessage = False
        self.setupUi(self)
        self.clear_interface()

        self.start()
        self.interface()
        self.singner()
        self.create_testing()
        self.show()

    def start(self):
        # socket客户端后台线程
        self.client_thread1 = threading.Thread(target=client.client_connect)
        self.client_thread1.setDaemon(True)
        self.client_thread1.start()

        #发送在线的消息给服务端（没派上用场）
        self.client_thread2 = threading.Thread(target=client.send_alive)
        self.client_thread2.setDaemon(True)
        self.client_thread2.start()


    def singner(self):
        #信号
        self.pushButton.clicked.connect((lambda: self.tabWidget.setCurrentIndex(0)))
        self.pushButton_2.clicked.connect((lambda: self.tabWidget.setCurrentIndex(1)))
        self.pushButton_3.clicked.connect((lambda: self.tabWidget.setCurrentIndex(2)))
        self.pushButton_5.clicked.connect(self.start_test)

    '''
    def send_score(self):
        #算出分数
        fileName,fileType = QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(), "Jpg Files(*.jpg)")
        sc = compare(r'Question\1.jpg',fileName)
        if int(sc) == 0:
            sc = 100
        else:
            sc = 0
        self.lineEdit.setText(str(sc))
        msg = 'score'+json.dumps(f'[{sc},"{currect_name}"]',ensure_ascii=False)
        client.send_score(msg)
    '''

    def clear_interface(self):
        #清除设计时留下的不必要东西
        self.label.clear()
        self.listWidget.clear()

    def interface(self):
        #界面刷新
        self.message = client.client_connect()
        for i in json.loads(self.message[2]):
            self.listWidget.addItem(i['实验名'])
        # 设置欢迎信息
        self.textBrowser_2.setText(json.loads(self.message[1])['课程介绍'])
        # 设置默认选择第一个
        self.class_message = json.loads(self.message[2])
        self.listWidget.itemClicked.connect(self.show_class_message)

    def show_class_message(self,item):
        self.item_choose = item
        for i in range(len(self.class_message)):
            if self.class_message[i]['实验名'] == item.text():
                self.label.setText(self.class_message[i]['实验标题'])
                self.textBrowser.setText(self.class_message[i]['实验内容'])

    def show_class(self):
        # title
        self.label.setText('123')
        # content
        self.textBrowser.clear()
        self.textBrowser.append('内容')
    '''
    def get_response(self):
        #多余的功能
        while not self.isgetmessage:
            try:
                self.class_message = client.class_message
                self.welcome_message = client.welcome_message
                self.isgetmessage = True
            except:
                pass
    '''

    def start_test(self):
        vbox = QVBoxLayout()  # 纵向布局,主布局
        hbox = QHBoxLayout()
        anser1_hbox = QHBoxLayout()
        anser2_hbox = QHBoxLayout()
        anser3_hbox = QHBoxLayout()

        self.dialog = QWidget()
        self.dialog.resize(300, 400)
        self.anser_1 = QLineEdit()
        anser1_hbox.addWidget(QLabel('填写答案1：'))
        anser1_hbox.addWidget(self.anser_1)
        self.anser_2 = QLineEdit()
        anser2_hbox.addWidget(QLabel('填写答案2：'))
        anser2_hbox.addWidget(self.anser_2)
        self.anser_3 = QLineEdit()
        anser3_hbox.addWidget(QLabel('填写答案3：'))
        anser3_hbox.addWidget(self.anser_3)
        self.okBtn = QPushButton("提交答案")
        self.cancelBtn = QPushButton("取消考试")
        self.dialog.setWindowTitle("开始考试")

        # 绑定事件
        self.okBtn.clicked.connect(self.push_anser)
        self.cancelBtn.clicked.connect(self.cancel)
        # 布局
        vbox.addLayout(anser1_hbox)
        vbox.addLayout(anser2_hbox)
        vbox.addLayout(anser3_hbox)
        hbox.addWidget(self.okBtn)
        hbox.addWidget( self.cancelBtn)
        vbox.addLayout(hbox)
        self.dialog.setLayout(vbox)
        self.dialog.show()

        #self.dialog.setWindowModality(Qt.ApplicationModal)  # 该模式下，只有该dialog关闭，才可以关闭父界面
        #self.dialog.exec_()
    def create_testing(self):
        print(self.ran)
        self.label_3.setText(self.class_message[self.ran-1]['实验标题'])
        self.textBrowser_3.setText(self.class_message[self.ran-1]['实验内容'])
        self.pushButton_6.clicked.connect(self.push_anser_show)

    # 槽函数如下：
    def push_anser_show(self):
        vbox = QVBoxLayout()  # 纵向布局,主布局
        hbox = QHBoxLayout()
        anser1_hbox = QHBoxLayout()
        anser2_hbox = QHBoxLayout()
        anser3_hbox = QHBoxLayout()

        self.dialog = QWidget()
        self.dialog.resize(300, 400)
        self.anser_4 = QLineEdit()
        anser1_hbox.addWidget(QLabel('填写答案1：'))
        anser1_hbox.addWidget(self.anser_4)
        self.anser_5 = QLineEdit()
        anser2_hbox.addWidget(QLabel('填写答案2：'))
        anser2_hbox.addWidget(self.anser_5)
        self.anser_6 = QLineEdit()
        anser3_hbox.addWidget(QLabel('填写答案3：'))
        anser3_hbox.addWidget(self.anser_6)
        self.okBtn = QPushButton("提交答案")
        self.cancelBtn = QPushButton("取消测试")
        self.dialog.setWindowTitle("开始测试")

        # 绑定事件
        self.okBtn.clicked.connect(self.testing)
        self.cancelBtn.clicked.connect(self.cancel)
        # 布局
        vbox.addLayout(anser1_hbox)
        vbox.addLayout(anser2_hbox)
        vbox.addLayout(anser3_hbox)
        hbox.addWidget(self.okBtn)
        hbox.addWidget( self.cancelBtn)
        vbox.addLayout(hbox)
        self.dialog.setLayout(vbox)
        self.dialog.show()

    def push_anser(self):
        sc = 0
        if self.anser_list[self.listWidget.row(self.item_choose)][0] == self.anser_1.text():
            sc += 33
        if self.anser_list[self.listWidget.row(self.item_choose)][1] == self.anser_2.text():
            sc += 33
        if self.anser_list[self.listWidget.row(self.item_choose)][2] == self.anser_3.text():
            sc += 33
        #print ('得分:'+str(sc))
        msg_box = QMessageBox(QMessageBox.Warning, '得分：', '得分:'+str(sc))
        msg_box.exec_()
        self.dialog.close()

    def testing(self):
        print("已发送！")
        self.anser = []
        self.anser.append(login_name)
        self.anser.append(self.anser_4.text())
        self.anser.append(self.anser_5.text())
        self.anser.append(self.anser_6.text())
        sender = []
        #sender.append(self.listWidget.row(self.item_choose))
        sender.append(self.ran-1)
        sender.append(self.anser)
        msg = 'anser'+json.dumps(sender, ensure_ascii=False)
        client.send_score(msg)
        print (sender)
        msg_box = QMessageBox(QMessageBox.Warning, '提示：', '答案已提交给老师，请在教师端查看成绩！')
        msg_box.exec_()
        self.dialog.close()

    def cancel(self):
        print("已取消！")
        self.dialog.close()


class logindialog(QDialog):
    #登录界面
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('登录界面')
        self.resize(200, 200)
        self.setFixedSize(self.width(), self.height())
        self.setWindowFlags(Qt.WindowCloseButtonHint)

        ###### 设置界面控件
        self.frame = QFrame(self)
        self.verticalLayout = QVBoxLayout(self.frame)

        self.lineEdit_account = QLineEdit()
        self.lineEdit_account.setPlaceholderText("请输入账号")
        #self.lineEdit_account.setText('张三')

        self.verticalLayout.addWidget(self.lineEdit_account)

        self.lineEdit_password = QLineEdit()
        self.lineEdit_password.setPlaceholderText("请输入密码")
        #self.lineEdit_password.setText('admin')
        self.verticalLayout.addWidget(self.lineEdit_password)

        self.pushButton_enter = QPushButton()
        self.pushButton_enter.setText("确定")
        self.verticalLayout.addWidget(self.pushButton_enter)

        self.pushButton_quit = QPushButton()
        self.pushButton_quit.setText("取消")
        self.verticalLayout.addWidget(self.pushButton_quit)

        self.get_user()

        ###### 绑定按钮事件
        self.pushButton_enter.clicked.connect(self.on_pushButton_enter_clicked)
        self.pushButton_quit.clicked.connect(QCoreApplication.instance().quit)


    def get_user(self):
        # 获取用户列表，不在列表的不允许登录
        self.namelist = json.loads(client.log())
        self.name = []
        for n in self.namelist:
            self.name.append(n[1])
        self.name = self.name

    def on_pushButton_enter_clicked(self):
        # 点击登录
        global login_name
        login_name = self.lineEdit_account.text() #将用户名存起来
        if self.lineEdit_account.text() in self.name and self.lineEdit_password.text() == "admin":
            # 通过验证，关闭对话框并返回1
            global currect_name
            currect_name = self.lineEdit_account.text()
            self.accept()

        else:
            QMessageBox.warning(self, '提示', "用户名或密码错误")
            return


if __name__ == "__main__":
    #高分辨率屏幕适配
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    app =  QApplication(sys.argv)

    login = logindialog()
    if login.exec_() == QDialog.Accepted:
        students = Students()
        sys.exit(app.exec_())


